package com.zyk.script.manager;

import com.zyk.script.manager.holder.PropertiesHolder;
import com.zyk.script.manager.plugin.IScriptPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

public class ScriptManager {

    private static final Logger logger = LoggerFactory.getLogger(ScriptManager.class);

    private PropertiesHolder propertiesHolder;
    private Properties properties;

    public ScriptManager() {
        this(ScriptManager.class.getClassLoader());
    }

    public ScriptManager(ClassLoader classLoader) {
        this(classLoader, null);
    }

    public ScriptManager(ClassLoader classLoader,Properties properties) {
        this.propertiesHolder = new PropertiesHolder(classLoader);
        this.properties = properties;
    }

    public void run(String[] args) throws IOException {
        if(properties == null){
            properties = propertiesHolder.loadProperties();
        }
        doRunScript(args);
    }

    public void doRunScript(String[] args) {
        ServiceLoader<IScriptPlugin> scriptPlugins = ServiceLoader.load(IScriptPlugin.class);
        HashMap<String, IScriptPlugin> mapName2ScriptPlugin = new HashMap<>();
        for (IScriptPlugin scriptPlugin : scriptPlugins) {
            mapName2ScriptPlugin.put(scriptPlugin.getName(), scriptPlugin);
        }

        String pluginStr = properties.getProperty("script.enable.plugins", "");
        List<String> plugins = Arrays.asList(pluginStr.split(","));
        for (String plugin : plugins) {
            IScriptPlugin scriptPlugin = mapName2ScriptPlugin.get(plugin);
            if(scriptPlugin == null){
                logger.error("plugin :{} , not exist", plugin);
                continue;
            }
            try {
                scriptPlugin.run(args, properties);
            } catch (Exception e) {
                logger.error("plugin :{} , run error", plugin);
                logger.error("ERROR", e);
            }
        }
    }
}
